<template>
	<form class="margin-top app-form">
		<view class="cu-form-group">
			<view class="title">是否在职</view>
			<input disabled="true" :value="model.IsPayroll ? '是' : '否'" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title">工号</view>
			<input disabled="true" v-model="model.OpenId" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title" :class="{ 'required': !model.IsPayroll }">姓名</view>
			<input :disabled="model.IsPayroll" v-model="model.RealName" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title required">手机号</view>
			<input v-model="model.Phone" placeholder="" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title">性别</view>
			<input disabled="true" v-model="model.Gender" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title required">部门</view>
			<depart-selector v-model:value="model.DepartId" />
		</view>
		<view class="cu-form-group" >
			<view class="title required">证件类型</view>
			<dict-select v-model:value="model.CodeType" :bordered="false" dict="证件类型" prefix="" remove="教工号" />
		</view>
		<view class="cu-form-group" >
			<view class="title required">证件号</view>
			<input v-model="model.Code" name="input" class="text-right" />
		</view>
		<view class="cu-form-group" v-if="!model.IsPayroll">
			<view class="title required">开户行</view>
			<input v-model="model.BankName" placeholder="最多只能填写40字" name="input" class="text-right" />
		</view>
		<view class="cu-form-group" v-if="!model.IsPayroll">
			<view class="title required">银行卡号</view>
			<input v-model="model.CardNumber" placeholder="16-19位银行卡号,无空格" name="input" class="text-right" />
		</view>
		<view class="cu-form-group" v-if="!model.IsPayroll">
			<view class="title required">确认卡号</view>
			<input v-model="model.ConfirmCardNumber" placeholder="两次输入必须一致" name="input" class="text-right"
			 @change="model.ConfirmCardNumber = ''" />
		</view>
		<view class="cu-form-group">
			<view class="title required">监考校区</view>
			<dict-select v-model:value="model.CampusCode" :dict="campusOptions" prefix="" />
		</view>
		<view class="cu-form-group">
			<view class="title required">监考科目</view>
			<dict-select v-model:value="model.Level" :dict="levelOptions" prefix="" />
		</view>
		<view class="cu-form-group" v-if="model.CampusCode === '352012'">
			<view class="title required">乘车地点</view>
			<dict-select v-model:value="model.BoardLocation" dict="监考教师乘车地点" prefix="" />
		</view>
		<view class="cu-form-group">
			<view class="title">去年是否监考</view>
			<input disabled="true" :value="model.ParticipatedLastYear ? '是' : '否'" name="input" class="text-right" />
		</view>
		<view class="cu-form-group">
			<view class="title">预选考场</view>
			<dict-select v-model:value="model.Preselection" :dict="options" prefix="" />
		</view>
		<view class="cu-form-group">
			<view class="title">接受校区调剂</view>
			<switch @change="model.AcceptAdjustment = $event.detail.value"
				:class="model.AcceptAdjustment ? 'checked':''" :checked="model.AcceptAdjustment ? true : false">
			</switch>
		</view>
		<view class="cu-form-group">
			<view class="title">备注</view>
			<input v-model="model.value" name="input" class="text-right" placeholder="限50字" />
		</view>
		<button class="margin bg-blue lg" @click="onSubmit" :disabled="loading">报名</button>
		<view class="fixed">fixed</view>
	</form>
</template>

<script setup>
	import app from '@/app'
	import {
		ref,
		reactive,
		inject,
		h,
		watch
	} from 'vue'
	import axios from '@/axios'

	// -- 业务逻辑，点击确定后应该如何 -- //
	const exam = inject("exam");
	const buildings = inject("buildings");
	const application = inject("application");
	const emits = defineEmits(['onSubmit']);
	const modelRef = ref();
	const props = defineProps({
		isInWhiteList: {
			type: Boolean,
			default: false
		}
	})
	
	// STEP1: 填一个空模型
	const emptyModel = {
		ID: app.GUID_EMPTY,
		ExamId: exam.ID,
		RealName: "",
		Phone: "",
		Gender: "男",
		CodeType: "身份证",
		Code: "",
		BankName: "",
		CardNumber: "",
		ConfirmCardNumber: "",
		CampusCode: "352011",
		BoardLocation: "自行前往",
		Level: "",
		DepartId: app.GUID_EMPTY,
		ParticipatedLastYear: false,
		AttendTraining: false,
		Preselection: "",
		Status: 0,
		Cet4Room: "",
		Cet6Room: "",
		Money: 0,
		Memo: "",
		Status: 0,
		BuildingId: app.GUID_EMPTY,
		Name: "",
		OpenId: "",
		IsPayroll: false
	};
	const model = reactive({
		...emptyModel
	});

	// STEP3: 初始化数据
	let lastRead = "";
	async function getUserByCode(code) {
		if (code === lastRead) return;
		let msg = await axios.post("/api/applications/GetUserByCode", {
			code
		});
		if (msg.success) {
			let data = msg.data;
			model.Code = data.Code;
			model.CodeType = data.CodeType;
			model.Gender = data.Gender;
			model.RealName = data.RealName;
			model.DepartId = data.DepartId;
			model.BankName = data.BankName;
			model.CardNumber = data.CardNumber;
			model.Phone = data.Phone;
			model.ParticipatedLastYear = data.ParticipatedLastYear;
			model.IsPayroll = data.IsPayroll;
			model.OpenId = data.OpenId
		}
		lastRead = code;
	}

	watch(application, _ => {
		Object.assign(model, application);
		if (model.ID === app.GUID_EMPTY) {
			getUserByCode(app.currentUser.Code);
		} else {
			model.ConfirmCardNumber = model.CardNumber;
		}
	}, {
		immediate: true,
		deep: true
	});

	// STEP4: 初始化预选考场
	const options = reactive({
		name: "考场",
		entries: []
	});

	function generateOptions() {
		model.Preselection = "";
		const level = model.Level;
		const campusCode = model.CampusCode;
		let opts = [{
			DataKey: "",
			DataValue: "如果需要，可以在此预选考场"
		}];
		let data = buildings.value.find(e => e.CampusCode == campusCode) || {
			CampusCode: campusCode,
			Remains: []
		};
		for (let item of data.Remains) {
			let remain = 0;
			switch (level) {
				case "4":
					remain = item.Cet4Remain;
					break;
				case "6":
					remain = item.Cet6Remain;
					break;
				case "A":
					remain = Math.min(item.Cet4Remain, item.Cet6Remain)
					break;
				default:
					break;
			}

			if (remain !== 0) {
				opts.push({
					DataKey: item.BuildingName,
					DataValue: `${item.BuildingName}`,
					Enable: true
				});
			}
		}
		options.entries = opts;
	}

	const campusOptions = reactive({
		name: "监考校区",
		entries: []
	});
	const levelOptions = reactive({
		name: "科目级别",
		entries: []
	});

	function generateCampusOptions() {
		const level = model.Level;
		const campusCode = model.CampusCode;
		
		let opts = [{
				DataKey: "352011",
				DataValue: `思明校区`,
				Enable: props.isInWhiteList || (exam.SiMingRemain > 0),
			},
			{
				DataKey: "352012",
				DataValue: `翔安校区`,
				Enable: props.isInWhiteList || (exam.XiangAnRemain > 0),
			},
			{
				DataKey: "35611",
				DataValue: `漳洲校区`,
				Enable: false, // props.isInWhiteList || (exam.ZhangZhouRemain > 0),
			},
		];
		let levelOpts = [];
		if (props.isInWhiteList) {
			levelOpts = [
				{
					DataKey: "A",
					DataValue: `全天`,
				},
				{
					DataKey: "4",
					DataValue: `四级`,
				},
				{
					DataKey: "6",
					DataValue: `六级`,
				},
			];
		} else {
			switch (campusCode) {
				case "352011":
					levelOpts = [
						{
							DataKey: "A",
							DataValue: `全天(剩余 ${Math.min(exam.SiMingCet4Remain, exam.SiMingCet6Remain)} 位)`,
							Enable: !(exam.SiMingCet4Remain <= 0 || exam.SiMingCet6Remain < 0),
						},
						{
							DataKey: "4",
							DataValue: `四级(上午，剩余 ${exam.SiMingCet4Remain} 位)`,
							Enable: !(exam.SiMingCet4Remain <= 0),
						},
						{
							DataKey: "6",
							DataValue: `六级(下午，剩余 ${exam.SiMingCet6Remain} 位)`,
							Enable: !(exam.SiMingCet6Remain <= 0),
						},
					];
					break;
				case "352012":
					levelOpts = [{
							DataKey: "A",
							DataValue: `全天(剩余 ${Math.min(exam.XiangAnCet4Remain, exam.XiangAnCet6Remain)} 位)`,
							Enable: !(exam.XiangAnCet4Remain <= 0 || exam.XiangAnCet6Remain < 0),
						},
						{
							DataKey: "4",
							DataValue: `四级(上午，剩余 ${exam.XiangAnCet4Remain} 位)`,
							Enable: !(exam.XiangAnCet4Remain <= 0),
						},
						{
							DataKey: "6",
							DataValue: `六级(下午，剩余 ${exam.XiangAnCet6Remain} 位)`,
							Enable: !(exam.XiangAnCet6Remain <= 0),
						},
					];
					break;
				case "35611":
					levelOpts = [{
							DataKey: "A",
							DataValue: `全天(剩余 ${Math.min(exam.ZhangZhouCet4Remain, exam.ZhangZhouCet6Remain)} 位)`,
							Enable: !(exam.ZhangZhouCet4Remain <= 0 || exam.ZhangZhouCet6Remain < 0),
						},
						{
							DataKey: "4",
							DataValue: `四级(上午，剩余 ${exam.ZhangZhouCet4Remain} 位)`,
							Enable: !(exam.ZhangZhouCet4Remain <= 0),
						},
						{
							DataKey: "6",
							DataValue: `六级(下午，剩余 ${exam.ZhangZhouCet6Remain} 位)`,
							Enable: !(exam.ZhangZhouCet6Remain <= 0),
						},
					];
					break;
				default:
					break;
			}
		}
		
		campusOptions.entries = opts;
		levelOptions.entries = levelOpts;
	}

	watch(() => model.Level, _ => {
		generateOptions();
		generateCampusOptions();
	})
	watch(() => model.CampusCode, _ => {
		generateOptions();
		generateCampusOptions();
		model.Preselection = "";
		model.BoardLocation = "自行前往";
	}, {
		immediate: true
	});
	model.Preselection = application.Preselection;

	const formRef = ref("");

	function validate() {
		if (loading.value) {
			return;
		}
		
		if (!/^1[3-9]\d{9}$/.test(model.Phone)) {
			alert("手机号的格式不正确");
			return false;
		}
		if (model.DepartId === app.GUID_EMPTY) {
			alert("必须选择部门名称");
			return false;
		}
		
		var pattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
		if (model.CodeType === "居民身份证" && !pattern.test(model.Code)) {
			alert("身份证格式不正确");
			return false;
		} else {
			model.Code = model.Code.toUpperCase();
		}

		if (!model.IsPayroll) {
			if (model.BankName === "") {
				alert("必须填写开户行");
				return false;
			}

			if (model.BankName.length > 40) {
				alert("开户行不能超过40字");
				return false;
			}

			if (model.CardNumber.length > 19) {
				alert("银行卡号不能超过19位");
				return false;
			}

			if (model.CardNumber !== model.ConfirmCardNumber) {
				alert("两次输入的银行卡号不一致，请检查。");
				return false;
			}
		}

		if (model.Memo.length > 50) {
			alert("备注不能超过50字");
			return false;
		}

		return true;
	}
	const loading = ref(false);
	async function onSubmit() {
		try {
			// await formRef.value.validate();
			if (!validate()) {
				return;
			}
			loading.value = true;
			// STEP6：处理一下提交函数
			let msg = await axios.post("/api/applications/DashboardApplicate", model);
			if (!msg.success) {
				alert(msg.errorStrings)
				return;
			} else {
				Object.assign(model, msg.data);
				Object.assign(application, msg.data);
				alert(msg.msg);
				emits('onSubmit');
			}
		} catch (err) {

		} finally {
			loading.value = false;
		}
	};
</script>

<style lang="less">
	.app-form {
		.title {
			width: 7em;
			text-align: left;
			position: relative;

			&.required::after {
				content: '*';
				color: red;
				position: absolute;
				right: 10rpx;
			}
		}

		.fixed {
			font-size: 0;
		}
	}
</style>